#!/bin/python3
# encoding=utf-8

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import sys

CONFIG_SAMPLE_CNT = 20

CONFIG_GATE = 0

CONFIG_CSV = "/nfs/otdr-well.csv"
if len(sys.argv) > 1:
    CONFIG_CSV = sys.argv[1]
# CONFIG_CSV = "/nfs/otdr-well.csv"
# CONFIG_CSV = "max30102-first.csv"
# CONFIG_CSV = "max30102-1.csv"
# CONFIG_CSV = "9000-point.csv"



def calcGate(data):
    tmax = np.max(data[200:600])
    tmin = np.min(data[200:600])
    # return -2000
    return 0
    # return 148
    # return -2300
    return tmin + (tmax - tmax) * 1
def calcGate2(S, T = 50, sec = 10):
    if (len(S) < 200):
        pass
    
    A = np.linspace(0, len(S), int(len(S)/T)).astype(int)
    for a in A[0:-2]:
        # 默认每10秒取出一组数据
        # tick = calc_heartbeat(S[a:a + sec * T], T)
        tmax = np.max(S[a:a + sec * T])
        tmin = np.min(S[a:a + sec * T])
        print(tmax, tmin, tmax - (tmax - tmin)*0.4)

# A 只有0、1、-1三个值，计算1的个数可以退之某时间段有多少次心跳
# T 周期，多少个点表示1秒周期，例子里20采样点表示1周期
def calc_heartbeat(S, T=20):
    # [0]提取tuple
    # np.where() = (array([ 21,  38,  48,  67,  85, 103, 119, 136, 153, 169, 186, 205, 228]),)
    # A          =  array([ 21,  38,  48,  67,  85, 103, 119, 136, 153, 169, 186, 205, 228])
    A = np.where(S == 1)[0]
    # B 两个心跳之间差
    B = A[1:] - A[0:-1]
    # 60秒内心跳
    tick = T * 60 / np.average(B)
    return tick

# 打印每秒心率，以10秒内平均
def print_every_sec_heartbeat(S, T=20, sec = 10):
    if (len(S) < 200):
        pass
    
    A = np.linspace(0, len(S), int(len(S)/T)).astype(int)
    for a in A[0:-2]:
        # 默认每10秒取出一组数据
        tick = calc_heartbeat(S[a:a + sec * T], T)
        print("%0.2f" %(tick))


# ===============================================
fd = open(CONFIG_CSV)
data = pd.read_csv(fd)

# ===============================================
# S0：原始数据
S0 = data['data']
# 噪声基准备线
# noise = np.min(S0[30000:32000])
noise = np.max(S0[30000:32000])
# noise = np.average(S0[30000:32000])
S1 = S0 - noise
S2  = 0 - S1
S2 = S1

# 
S3 = np.where(S2 < 0, -S2, S2)
S4 = np.log(S3)
# S3 = np.log(S0)

plt.subplot(4, 1, 1)
plt.plot(S0, label="raw")
plt.legend()

plt.subplot(4, 1, 2)
plt.plot(S1, label="+")
plt.legend()

plt.subplot(4, 1, 3)
plt.plot(S2, label="log(S)")
plt.legend()

plt.subplot(4, 1, 4)
plt.plot(S4, label="log(S-noise)")
plt.legend()
# plt.scatter(S22, S22)
# hist, bins = np.histogram(S22, bins=[-4000, -3000, -2000, -1000,-500, 0, 500,  1000,2000, 3000, 4000])
# plt.plot(data['lr'])
plt.show()


